#!/usr/bin/env python

import xml.dom.minidom

from DataRow import *

class DataTable(list):
    
    def _get_schema(self):
        return self.__schema
    
    def _get_name(self):
        return self.__name
    def _set_name(self, name):
        self.__name = name
        
    def _get_column_relations(self):
        return self.__column_relations
    
    schema = property(_get_schema)
    name = property(_get_name, _set_name)
    column_relations = property(_get_column_relations)
    
    def __init__(self, schema, name = None):
        self.__rows = list()
        self.__schema = schema
        self.__column_relations = dict()
        
        if (name is None):
            name = schema.Name
        
        self.name = name
        
    def create_row(self):
        return DataRow(self)
    
    def add_row(self, row):
        if (row.table != self):
            raise Exception()
        if (self.count(row) > 0):
            raise Exception()
        self.append(row)
        row.row_state = DataRowState.New
        
    
    def load_file(self, file):
        xmlDom = xml.dom.minidom.parse(file)
        self.load_xml(xmlDom)
    
    def load_xml(self, xmlDom):
        if (not xmlDom.tagName == "DataTable"):
            raise Exception()
        
        self.name = xmlDom.getAttribute("name")
        
        for node in xmlDom.getElementsByTagName("DataColumnRelation"):
            columnRelation = DataColumnRelation(self)
            columnRelation.load_xml(node)
    
    def save_file(self, filePath):
        pass
    
    def save_xml(self):
        pass
    
class DataColumnRelation:
    def _get_column(self):
        return self.__column
    def _set_column(self, column):
        self.__column = column
    
    def _get_table(self):
        return self.__table
    def _set_table(self, table):
        self.__table = table
    
    def _get_parent_table(self):
        return self.__parent_table
    def _set_parent_table(self, parentTable):
        self.__parent_table = parentTable
        
    column = property(_get_column, _set_column)
    table = property(_get_table, _set_table)
    parent_table = property(_get_parent_table, _set_parent_table)
    
    def __init__(self, table, column = None, parentTable = None):
        self.column = column
        self.parent_table = parentTable
        self.table = table
    
    def load_file(self, filePath):
        pass
    
    def load_xml(self, xmlDom):
        if (not xmlDom.tagName == "DataColumnRelation"):
            raise Exception()
        
        columnName = xmlDom.getAttribute("column")
        self.column = self.table.schema[columnName]
        
        parentTableName = xmlDom.getAttribute("parent_table")
        self.parent_table = self.table.schema.dataset.tables[parentTableName]
    
    def save_file(self, filePath):
        pass
    
    def save_xml(self):
        pass